$(function () {
    layui.use(['laydate','laytpl', 'table','form','formSelects','layer','util', 'soulTable','element'], function () {
        var laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            layer = layui.layer,
            util = layui.util,
            soulTable = layui.soulTable,
            element = layui.element;
        var areaArr = [], allMeters = [], flag = 0, tbIndex = null,
            max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');

        initAll();
        function initAll(){
            initDate();
            getAllMeters();
            showChartFrame()
        }
        function initDate(){
            var startDate = laydate.render({
                elem: '#startTime'
                ,value: new Date()
                , format: 'yyyy-MM-dd'
                , max: max
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
            var endDate = laydate.render({
                elem: '#endTime'
                ,value: new Date()
                , format: 'yyyy-MM-dd'
                , max: max
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
        }

        function showChartFrame(){
            initChartDate();
            getPieDate();
        }

        function initChartDate(){
            laydate.render({
                elem: '#chart-st'
                ,value: new Date()
                , format: 'yyyy-MM-dd'
                , type: 'month'
                , max: max
                , done: function(value, date, endDate){
                    getPieDate();
                }
            });
            laydate.render({
                elem: '#chart-et'
                ,value: new Date()
                , format: 'yyyy-MM-dd'
                , type: 'month'
                , max: max
                , done: function(value, date, endDate){
                    getPieDate();
                }
            });
        }

        function getAllAreas(){
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function(html){
                            $('.areaMenu').html(html);
                            formSelects.render('areaMenu');
                            formSelects.btns('areaMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('areaMenu', 'val');
                            var initarea = result.map(function(item){
                                return item.areaId
                            });
                            formSelects.value('areaMenu', initarea);
                            areaArr.length = 0;
                            areaArr =  JSON.parse(JSON.stringify(result));
                            filterMeters(areaArr);
                        });
                    }
                }
            });
        }

        function getAllMeters(){
            $.ajax({
                type: "GET",
                url: ctx + "/report/getAllMeters.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allMeters = result;
                        getAllAreas();
                    }
                }
            });
        }

        function filterMeters(areaArr){
            var list = [];
            allMeters.forEach(function(item){
                areaArr.forEach(function(val){
                    if(item.areaId == val.areaId){
                        list.push({"name": val.areaName, "type": "optgroup"});
                        list.push({"name": item.deviceName + '_' + item.anotherName, "value": item.meterCode});
                    }
                });
            });
            formSelects.data('select-meter', 'local', {
                arr: uniqObjInArray(list)
            });
            formSelects.btns('select-meter', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
            formSelects.value('select-meter', 'val');
            var initmeter = list.map(function(item){
                return item.value
            });
            formSelects.value('select-meter', initmeter);
            $(".refreshBtn").click();
        }

        // 监听区域多选
        formSelects.on('areaMenu', function(id, vals, val, isAdd, isDisabled){
            areaArr.length = 0;
            vals.forEach(function(item){
                areaArr.push({"areaId" :item.value, "areaName" : item.name});
            });
            filterMeters(areaArr);
        }, true);

        // 监听设备多选
        formSelects.on('select-meter', function(id, vals, val, isAdd, isDisabled){
            $(".refreshBtn").click();
        }, true);

        //判断权限
        function hasAuth(authCode) {
            var authArray=authStr.split(",");
            if(authArray&&authArray.length>0){
                for(var i=0;i<authArray.length;i++){
                    if(authArray[i].trim()==authCode){
                        return true;
                    }
                }
            }
            return false;
        }

        //点击刷新
        $('.searchBtn').click(function(){
            $(".refreshBtn").click();
        });
        $(".refreshBtn").click(function () {
            form.on('submit(search)', function(data){
                // console.log(data.field);
                getDevices(data.field);
                return false;
            });
        });

        function getDevices(datas) {
            // $.ajax({
            //     type: "POST",
            //     url: ctx + "/report/queryReport.do",
            //     data: datas,
            //     dataType: "json",
            //     success: function (result) {
            //         if (result.statusCode == "OK") {
            //         // var data = result.data;
            //             var data = resultdata.filter(function (item) {
            //                 return item.areaId === areaId
            //             });
            //             renderTable(data);
            //     }
            //     }
            // });
            renderTable();
        }

        //勾选的水表表格
        function renderTable(data) {
            var tbHeigth = $('.main-part').height();
            var data = [
                {id:1,areaName:'测试区',anotherName:'110_测试110',imgurl:'',rectime: '2020-09-25 16:00:00',readnum:'21',status:'OK'}
            ];
            tbIndex = table.render({
                elem: '#reports'
                , id: 'myTable'
                , data: data
                , heigth: tbHeigth
                , drag: false
                , title: '数据管理报表'
                , defaultToolbar:[]
                , cols: [[
                    {field: 'areaName', title: '区域', width: 120}
                    , {field: 'anotherName', title: '设备'}
                    , {field: 'rectime', title: '时间'}
                    , {field: 'readnum', title: '读数'}
                    , {field: 'picture', title: '拍照', width: 80, templet: '#tools-tpl'}
                    , {field: 'imgurl', title: '图片',templet: '#imgTpl'}
                    , {field: 'status', title: '异常原因',width: 130, templet: '#sel-tpl'}
                    , {field: 'note', title: '备注 <i class="layui-icon layui-icon-about tips" title="双击单元格可输入"></i>', edit: 'text'}
                ]]
                , page: {
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 5  //每页显示条数
                    , limits: [15, 30, 45, 60]
                }
                , totalRow: false
                , loading: true
                , done:function(res, curr, count){
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                    soulTable.render(this);
                }
            });
        }

        function getPieDate(){
            var scaleData = [
                {
                    'name': '图片不清晰',
                    'value': 1
                },
                {
                    'name': '识别错误',
                    'value': 2
                },
                {
                    'name': '光线问题',
                    'value': 3
                },
                {
                    'name': '位置偏移',
                    'value': 4
                }

            ];
            renderPie(scaleData);
        }

        function renderPie(scaleData){
            var myChart = echarts.init(document.getElementById('chartbox'),'darkTheme');
            var rich = {
                white: {
                    color: '#fff',
                    align: 'center',
                    // fontWeight:'bold',
                    padding: [3, 0]
                }
            };
            var placeHolderStyle = {
                normal: {
                    label: {
                        show: false
                    },
                    labelLine: {
                        show: false
                    },
                    color: 'rgba(0, 0, 0, 0)',
                    borderColor: 'rgba(0, 0, 0, 0)',
                    borderWidth: 0
                }
            };
            var data = [];
            var color1 = ['rgb(255, 153, 153)', 'rgb(255, 176, 63)', 'rgb(61, 186, 45)', 'rgb(43, 166, 254)','rgb(255,222,0)','rgb(255,0,0)'];
            for (var i = 0; i < scaleData.length; i++) {
                data.push({
                    value: scaleData[i].value,
                    name: scaleData[i].name,
                    itemStyle: {
                        normal: {
                            borderWidth: 4,
                            shadowBlur: 2,
                            borderColor:color1[i],
                            shadowColor: color1[i],
                            color: color1[i],
                            opacity:0.55,
                        }
                    }
                }, {
                    value: 2,
                    name: '',
                    itemStyle: placeHolderStyle
                });
            }
            var seriesObj = [{
                name: '',
                type: 'pie',
                clockWise: false,
                radius: ['20%', '50%'],
                center: ['50%', '55%'],
                hoverAnimation: false,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            position: 'outside',
                            fontWeight:'bold',
                            formatter: function(params) {
                                var percent = 0;
                                var total = 0;
                                for (var i = 0; i < scaleData.length; i++) {
                                    total += scaleData[i].value;
                                }
                                percent = ((params.value / total) * 100).toFixed(0);
                                if(params.name !== '') {
                                    return params.name + '\n{white|' +  params.value +'个，占' + percent + '%}';
                                }else {
                                    return '';
                                }
                            },
                            rich: rich
                        },
                        labelLine: {
                            show: true,
                        }
                    }
                },
                data: data
            }];
            var option = {
                tooltip: {
                    show: false
                },
                legend: {
                    show: false
                },
                series: seriesObj
            };
            myChart.setOption(option);
        }

        $('.minimize').click(function(){
            $(this).addClass('layui-hide');
            $('.restore').removeClass('layui-hide');
            $('.precision .chart-wrap').addClass('minStyle');
        });
        $('.restore').click(function(){
            $(this).addClass('layui-hide');
            $('.minimize').removeClass('layui-hide');
            $('.precision .chart-wrap').removeClass('minStyle');
        });

        table.on('tool(daTable)', function (obj) {
            var data = obj.data;
            if(obj.event === 'stop'){
                progressBar('stop');
            }else if (obj.event === 'showPic') {
                layer.photos({
                    photos: '#pic_' + data.id,
                    //0-6的选择，指定弹出图片动画类型，默认随机
                    anim: 5
                });
            }else if(obj.event === 'takePicture'){
                var imgurl = 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2673450152,2628930507&fm=26&gp=0.jpg';
                data.imgurl = imgurl;
                $(this).parents('[data-field="picture"]').siblings('[data-field="imgurl"]').find('img').attr('src',imgurl);
            }else if(obj.event === 'recover'){
                progressBar('recover');
            }
        });

        function progressBar(type) {
            var layerIdx = layer.open({
                type: 0,
                title: false,
                closeBtn: 0,
                btn: false,
                area: '800px',
                content: $('#progress-tpl').html(),
                success: function (layero) {
                    element.init();
                    var text = type == 'stop' ? '暂停中。。。' : '恢复中。。。';
                    layero.find('.text').text(text);
                }
            });
            // 模拟进度条
            var per = 0, total = 100, timer = null;
            if(timer){
                clearInterval(timer);
            }else{
                timer = setInterval(function(){
                    if(per > total){
                        var text = type == 'stop' ? '已暂停' : '已恢复';
                        $('.text').text(text);
                        setTimeout(function(){
                            layer.close(layerIdx);
                        }, 500)
                    }else{
                        element.progress('progress', parseInt(per/total*100) +'%');
                        per += 2;
                    }
                }, 100);
            }
        }



            // 导出excel
        $('.exportBtn').click(function () {
            soulTable.export('myTable', {filename: '精度分析表.xlsx'});
        });

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                ptitle = $('<div class="ptitle">' + $('#printcontent .title').text() + '</div>');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            // 所有数据加载为新表格
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }
    });
});
